package org.swingDemo.UI;

import cn.hutool.core.io.FileUtil;
import com.esotericsoftware.tablelayout.swing.Table;

import javax.swing.*;
import java.awt.*;

public class FoldChooserPanel extends JPanel {

    private String panelTitle;

    private JTextField filePathField;
    private JButton chooseButton;

    public FoldChooserPanel(String title) {
        super(new BorderLayout());
        this.panelTitle = title;

        initPanel();
    }

    public String getFilePath() {
        return filePathField.getText();
    }

    private void initPanel() {
        filePathField = new JTextField();
        filePathField.setEnabled(false);
        chooseButton = new JButton("选择文件夹");
        chooseButton.addActionListener(l -> {
            onChooseFolder();
        });

        Table table = new Table();
        table.addCell(filePathField).expandX().fillX();
        table.addCell(chooseButton);

        this.setBorder(BorderFactory.createTitledBorder(panelTitle));
        this.add(table);
    }

    private void onChooseFolder() {
        JFileChooser fileChooser = new JFileChooser();
        String filePath = filePathField.getText();
        if (filePath.isEmpty()) {
            filePath = "D:/Test";
        }
        fileChooser.setCurrentDirectory(FileUtil.file(filePath));
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int option = fileChooser.showOpenDialog(MainFrame.mainFrame);
        if (option == JFileChooser.APPROVE_OPTION) {
            filePathField.setText(fileChooser.getSelectedFile().getAbsolutePath());
        }
    }
}
